package purchaseOrder

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/apps/purchase/auth"
	"insighttracking/common/enum"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/purchase/internal/svc"
	"insighttracking/apps/purchase/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetPurchaseOrderPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetPurchaseOrderPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetPurchaseOrderPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetPurchaseOrderPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetPurchaseOrderPageApiLogic) GetPurchaseOrderPageApi(req *types.GetPurchaseOrderPageReq) (resp *types.GetPurchaseOrderPageResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	pageRespBos, count, err := service.PurchaseOrderService.GetPurchaseOrderPageApi(l.ctx, accountInfo.EnterpriseId, bo.GetPurchaseOrderPageReqBo{
		SupplierID:           req.SupplierID,           // 供应商,关联到supplier表主键id
		PurchaserID:          req.PurchaserID,          // 采购员,关联到
		ExpectationGoodsDate: req.ExpectationGoodsDate, // 期望收货日期
		Types:                req.Types,                // 类型,0表示供应商创建,1表示现场采购
		OrderNo:              req.OrderNo,              // 操作流水号
		PageSize:             req.PageSize,             // 当前条数
		PageNumber:           req.PageNumber,           // 当前页数
	})
	if err != nil {
		return &types.GetPurchaseOrderPageResp{
			Data: make([]types.PurchaseOrdersModel, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}

	var resultList = make([]types.PurchaseOrdersModel, 0)
	for _, item := range pageRespBos {
		// 查询完成的数量
		detailEntities, err := service.PurchaseOrderDetailService.GetByPurchaseOrderIdApi(l.ctx, []int64{item.ID})
		var purchaseOrdersDetailStatusMap = make(map[int64][]*model.PurchaseOrdersDetailEntity)
		if err == nil && len(detailEntities) > 0 {
			purchaseOrdersDetailStatusMap = k.GroupBy(detailEntities, func(item *model.PurchaseOrdersDetailEntity) int64 {
				return item.StoreStatus
			})
		}
		entities, isOk := purchaseOrdersDetailStatusMap[10] // 找到已经入库的
		if isOk {
			if len(entities) == len(detailEntities) {
				item.StoreStatus = enum.PurchaseOrderStoreEnum
			} else {
				item.StoreStatus = enum.PurchaseOrderStorePartEnum
			}
		} else {
			item.StoreStatus = enum.PurchaseOrderStoreWaitEnum
		}
		resultList = append(resultList, types.PurchaseOrdersModel{
			ID:                   item.ID,                                                                                         // 主键id
			EnterpriseID:         item.EnterpriseID,                                                                               // 关联到enterprise表主键id
			SupplierID:           item.SupplierID,                                                                                 // 供应商,关联到supplier表主键id
			SupplierName:         item.SupplierName,                                                                               // 供应商,关联到supplier表主键id
			PurchaserID:          item.PurchaserID,                                                                                // 采购员,关联到
			PurchaserName:        item.PurchaserName,                                                                              // 采购员,关联到
			ExpectationGoodsDate: k.If(item.ExpectationGoodsDate.IsZero(), 0, utils.TimestampToString(item.ExpectationGoodsDate)), // 期望收货日期
			PurchaserTotalCount:  item.PurchaserTotalCount.StringFixed(2),                                                         // 采购总数量
			PurchaserTotalAmount: item.PurchaserTotalAmount.StringFixed(2),                                                        // 采购总金额
			Types:                item.Types,                                                                                      // 类型,0表示供应商创建,1表示现场采购
			Status:               item.Status,                                                                                     // 状态,-1表示取消订单,0表示待收货,10表示部分收货,20表示全部收货,30表示取消订单,40表示退货
			StoreStatus:          item.StoreStatus,                                                                                // 入库状态,0表示待入库,1表示部分入库,2表示已入库
			Remark:               item.Remark,                                                                                     // 备注
			CreatedAt:            utils.TimestampToString(item.CreatedAt),                                                         // 创建时间
			UpdatedAt:            utils.TimestampToString(item.UpdatedAt),                                                         // 更新时间
			OrderNo:              item.OrderNo,                                                                                    // 操作流水号
			TotalCount:           int64(len(detailEntities)),                                                                      // 总数量
			CompleteCount:        k.If(isOk, int64(len(entities)), 0),                                                             // 完成数量

		})
	}
	return &types.GetPurchaseOrderPageResp{
		Data: resultList,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
